<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

function isEn(){
    if(cookie('langIsZh')) return false;
    if(cookie('langIsNotZh')) return true;
    $lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
    if(!strstr($lang, 'zh')) return true;
    return false;
}
function timeString($time,$isEn = false)
{
    $day = strtotime(date('Y-m-d',time()));
    $pday = strtotime(date('Y-m-d',strtotime('-1 day')));
    $nowtime = time();

    $tc = $nowtime-$time;
    if(isEn()){
        if($time<$pday){
            $str = date('F d Y',$time);
        }elseif($time<$day && $time>$pday){
            $str = "yesterday ". date('H',$time);
        }elseif($tc>60*60){
            $str = floor($tc/(60*60))."hours ago";
        }elseif($tc>60){
            $str = floor($tc/60)."minuts ago";
        }else{
            $str = "now";
        }
        return $str;
    }
    if($time<$pday){
        $str = date('Y-m-d',$time);
    }elseif($time<$day && $time>$pday){
        $str = "昨天". date('H',$time)."时";
    }elseif($tc>60*60){
        $str = floor($tc/(60*60))."小时前";
    }elseif($tc>60){
        $str = floor($tc/60)."分钟前";
    }else{
        $str = "刚刚";
    }
    return $str;
}
function isIE() { 
    $userbrowser = $_SERVER['HTTP_USER_AGENT']; 
    if ( preg_match( '/MSIE/i', $userbrowser ) ) { 
        $usingie = true; 
    } else { 
        $usingie = false; 
    } 
    return $usingie; 
}
function isWeixin() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    return strpos($user_agent, 'MicroMessenger');
    if (strpos($user_agent, 'MicroMessenger') === false) {
// 非微信浏览器禁止浏览
        $ret = "HTTP/1.1 401 Unauthorized";
    } else {
// 微信浏览器，允许访问
        $ret = "MicroMessenger";
// 获取版本号
        preg_match('/.*?(MicroMessenger\/([0-9.]+))\s*/', $user_agent, $matches);
        $ret = '<br>Version:' . $matches[2];
    }
    return $ret;
}
// function isWeixin() {
//   $user_agent = $_SERVER['HTTP_USER_AGENT'];
//   return strpos($user_agent, 'MicroMessenger');
// }

function httpGet($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
// 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
// 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($curl, CURLOPT_URL, $url);

    $res = curl_exec($curl);
    curl_close($curl);

    return $res;
}

function httpPost($url,$data) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    $res = curl_exec($curl);
    curl_close($curl);

    return $res;
}

function ajaxClean(){
    foreach($_GET as $x => $y ){
        $s = split("#",$x);
        if(count($s)>1){
            $_GET[$s[0]] = $y;
            unset($_GET[$x]);
        }
    }
    foreach($_POST as $x => $y ){
        $s = split("#",$x);
        if(count($s)>1){
            $_POST[$s[0]] = $y;
            unset($_POST[$x]);
        }
    }
}

function keywordSQL($keyword ,$database){
    if(!$keyword){
        return "";
    }
    foreach(explode(" ",$keyword) as $k){
        if(!$k){continue;}
        $k = addslashes($k);
        foreach(explode(",",$database) as $d){
            $sql[] = "( $d LIKE '%$k%' )";
        }
    }
    $keyword = implode(" OR ",$sql);
    if(count($sql)){
        $keyword = "($keyword)";
    }
    return $keyword;
}
function getPhpFile($filename){
    return json_decode(preg_replace("/(\/\*[\s\S]+?\*\/|\/\/[^\n]*)/", "",trim(substr(file_get_contents($filename), 15))),1);
}
// use think\Session;
function recordFrom(){
    // session_start();
    if(!session('from')){
//$_SERVER['HTTP_REFERER'];
        $url = parse_url( $_SERVER['HTTP_REFERER']);
        $host = $url['host'];
        if($host){
            $from[]=$host;
        }elseif(isWeixin()){
            $from[]="wxapp";
        }
        if($_GET['from']){$from[]=$_GET['from'];}
        if($from){
            session('from',implode(":",$from));
            // $_SESSION['from'] = implode(":",$from);
//$_GET['from'];
        }else{
            session('from','-');
            // $_SESSION['from'] = '-';
        }
    }
}
// recordFrom();
function getFrom(){
    return session('from');
}
function getIp(){
    if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
        $cip = $_SERVER["HTTP_CLIENT_IP"];
    } elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
        $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    } elseif (!empty($_SERVER["REMOTE_ADDR"])) {
        $cip = $_SERVER["REMOTE_ADDR"];
    } else {
        $cip = false;
    }
    return $cip;
}
function getTemplate($demand, $noCache = false){
    if(config("app_debug")){
        cache("$demand.template",null);
    }else{
        if($template = cache("$demand.template")) return $template;
    }
    $file_path = "../application/".request()->module()."/template/$demand.template.html";
    $template = file_get_contents($file_path);
    cache("$demand.template",$template,3600);
    return $template;
}
function getConfig($demand, $noCache = false){
    if(config("app_debug")){
        cache("$demand.config",null);
    }else{
        if($config = cache("$demand.config")) {
            return $config;
        }
    }
    $module = config('config_module');
    if(!$module){
        $module = request()->module();
    }
    $file_path = "../application/".$module."/config/$demand.config.json";
    $config = json_decode(preg_replace("/(\/\*[\s\S]+?\*\/|\/\/[^\n]*)/", "",trim(file_get_contents($file_path))),1);
    cache("$demand.config",$config,3600);
    return $config;
}
function getQrcode($url, $level = 5, $size = 10) {
    vendor('PHPQrcode');
    //引用phpqrcode文件
    $errorCorrectionLevel = intval($level); 
    //容错级别 intval()函数变量转换整形
    $matrixPointSize = intval($size);
    //生成图片大小 
    //生成二维码图片
    $object = new \QRcode();
    $object->png($url, false, $errorCorrectionLevel, $matrixPointSize, 2);
    die();
}
function getBarcode(){
    
}
function vcodeCreate($fontSize = 20, $length = 4) {
    //验证码字体大小
    $Verify = new \think\Verify();
    $Verify->fontSize = $fontSize;
    $Verify->length = $length;
    $Verify->entry();
    die();
}
function vcodeCheck($code, $id = '') {
    $verify = new \think\Verify();
    $a = $verify->check($code, $id);
    if (!$a) {
        return array('state' => 0, 'errormsg' => 'verify error');
    }
    return array('state' => 1);
}
function getIpInfo() {
    $apikey = config('BAIDU_API_KEY');
    $ip = getIp();
    $ch = curl_init();
    $url = "http://apis.baidu.com/apistore/iplookupservice/iplookup?ip=$ip";
    $header = array(
        "apikey: $apikey",
        );
    // 添加apikey到header
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // 执行HTTP请求
    curl_setopt($ch, CURLOPT_URL, $url);
    $res = curl_exec($ch);
    curl_close ( $ch );
    $res = json_decode($res, true);
    $res['data'] = $res['retData'];
    //var_dump($ip,$url,$res);
    return $res;
}
/*
把用户输入的文本转义（主要针对特殊符号和emoji表情）
*/
function userTextEncode($str){
    if(!is_string($str))return $str;
    if(!$str || $str=='undefined')return '';

    $text = json_encode($str); 
//暴露出unicode
    $text = preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i",function($str){
        return addslashes($str[0]);
    },$text); 
//将emoji的unicode留下，其他不动，这里的正则比原答案增加了d，因为我发现我很多emoji实际上是\ud开头的，反而暂时没发现有\ue开头。
    return json_decode($text);
}
/*
解码上面的转义
*/
function userTextDecode($str){
    $text = json_encode($str); 
//暴露出unicode
    $text = preg_replace_callback('/\\\\\\\\/i',function($str){
        return '\\';
    },$text);
//将两条斜杠变成一条，其他不动
    return json_decode($text);
}
//qq图片转换
function ubbReplace($str) {
    $str = str_replace ( ">", '<；', $str );
    $str = str_replace ( ">", '>；', $str );
    $str = str_replace ( "\n", '>；br/>；', $str );
    $str = preg_replace ( "[\[em_([0-9]*)\]]", "<img src=\"http://$_SERVER[SERVER_NAME]/qqFace/arclist/$1.gif\" />", $str );
    return $str;
}

//二维数组去掉重复值 并保留键值
function more_array_unique($arr=array())
{
    $arr_inner_key = [];
    foreach ($arr[0] as $k => $v) {
        $arr_inner_key[] = $k;   //先把二维数组中的内层数组的键值记录在在一维数组中
    }
    $temp = [];
    foreach ($arr as $k => $v) {
        $v = join('-||', $v);    //降维 用implode()也行
        $temp[$k] = $v;      //保留原来的键值 $temp[]即为不保留原来键值

        $temp = array_unique($temp);    //去重：去掉重复的字符串
        $arr_after = [];
        foreach ($temp as $k => $v) {
            $a = explode('-||', $v);   //拆分后的重组 如：Array( [0] => james [1] => 30 )
            $arr_after[$k] = array_combine($arr_inner_key, $a);  //将原来的键与值重新合并
        }
        //ksort($arr_after);//排序如需要：ksort对数组进行排序(保留原键值key) ,sort为不保留key值
        return $arr_after;
    }
}

//递归获取子孙
function recursion($arr,$id){
    $a = [];
    foreach ($arr as $v){
        if($v['rank'] == $id){
            $v['children'] = recursion($arr,$v['role_id']);
            if($v['children'] == null){
                unset($v['children']);
            }
            $a[] = $v;
        }
    }

    return $a;
}